$(function () {
    laypage.dir = '/res/lib/laypage/skin/laypage.css ';
    // if (window.localStorage.getItem('role') != "4") {
    //     $("#caozuo").remove()
    // }

    function memberTbody(list) {
        var _role = [
            {r: "0", t: "测试用户"},
            {r: "1", t: "未注册用户"},
            {r: "2", t: "普通用户"},
            {r: "3", t: "房间总管"},
            {r: "4", t: "管理员"},
            {r: "5", t: "财务"},
            {r: "6", t: "房管1"},
            {r: "7", t: "房管2"},
            {r: "8", t: "房管3"},
            {r: "9", t: "房管4"}
        ]
        var str = '';
        var role = window.localStorage.getItem('role');
        var modifyRole = '<a class="userUpdate">修改权限</a>';
        var addJf = '<a class="addjf">添加积分</a>';
        var minusJf = '<a class="remjf">扣除积分</a>';
        for (var i = 0; i < list.length; i++) {
            str += '<tr data-id="' + list[i].id + '" data-token="' + list[i].token + '" data-role="' + list[i].role + '" data-ep="' + list[i].earningsPercent + '">' +
                '<td>' + list[i].realName + '</td>' +
                '<td>' + list[i].userName + '</td>' +
                '<td>' + list[i].passWord + '</td>' +
                // '<td>' + (list[i].onlineStatus < 0 ? "离线" : "正常") + '</td>' +
                // '<td>' + (list[i].isDelete < 0 ? "删除" : "正常") + '</td>' +
                // '<td>' + (role == 4 ? list[i].role : "--") + '</td>' +
                '<td>' + list[i].integral + '</td>' +
                '<td>' + (new Date(list[i].createTime)).format("yyyy-MM-dd hh:mm:ss") + '</td>' +
                '<td>' + (new Date(list[i].lastLoginTime)).format("yyyy-MM-dd hh:mm:ss") + '</td>' +
                '<td>' + _role[list[i].role].t + '</td>' +
                '<td>' + (list[i].referrer ? list[i].referrer : "--") + '</td>' +
                '<td>' + (list[i].invCode ? list[i].invCode : "--") + '</td>' +
                '<td><a class="detailjf" href="#/member-page/' + list[i].id + '">明细</a></td>' + (function () {
                    if (window.localStorage.getItem('role') == "4") {
                        return '<td>' + modifyRole + '|' + addJf + '|' + minusJf + ($.inArray(list[i].role,["3","4","6","7","8","9"]) != -1 ? '|<a class="chichen">吃成比例</a>' : "") + '</td>'
                    } else {
                        return '<td>' + modifyRole + ($.inArray(list[i].role,["3","4","6","7","8","9"]) != -1 ? '|<a class="chichen">吃成比例</a>' : "") + '</td>';
                    }
                }()) +
                '</tr>'
        }

        return str
    }

    $('.export1').click(function () {
        var token = window.localStorage.getItem('token');
        var realName = $("#realName").val() || "";
        var username = $("#username").val() || "";
        var referrer = $("#referrer").val() || "";
        $('#dividend-print2').attr("action", "/user/doExportQuery?token=" + token + "&realName=" + realName + "&username=" + username + "&referrer=" + referrer);
        $('#dividend-print2').submit();
    });

    function roleList(r) {
        var _role = [
            {r: "0", t: "测试用户"},
            {r: "2", t: "普通用户"},
        ]

        if (r == "4") {
            return _role.concat([{r: "3", t: "房间总管"},
                {r: "6", t: "房管1"},
                {r: "7", t: "房管2"},
                {r: "8", t: "房管3"},
                {r: "9", t: "房管4"}])
        }


        if (r == "3") {
            return _role.concat([
                {r: "6", t: "房管1"},
                {r: "7", t: "房管2"},
                {r: "8", t: "房管3"},
                {r: "9", t: "房管4"}])
        }

        if (r == "6") {
            return _role.concat(
                [
                    {r: "7", t: "房管2"},
                    {r: "8", t: "房管3"},
                    {r: "9", t: "房管4"}]
            )
        }

        if (r == "7") {
            return _role.concat(
                [
                    {r: "8", t: "房管3"},
                    {r: "9", t: "房管4"}]
            )
        }

        if (r == "8") {
            return _role.concat(
                [
                    {r: "9", t: "房管4"}]
            )
        }
        if (r == "9") {
            return _role
        }

        return _role
    }


    function layerUserSet(owners, opts) {
        return '<div style="padding: 10px 0"> ' +

            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">用户名:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7"><input type="text" value="' + opts.userName + '" class="user-userName form-control"><div class="error alert alert-danger" ><strong></strong></div></div>' +
            '</div>' +

            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">密码:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7"><input type="text" value="' + opts.passWord + '" class="user-passWord form-control"></div>' +
            '</div>' +
            (function (role) {
                var _role = roleList(role)


                return '<div class="form-group">' +
                    '<label class="col-sm-3 control-label">权限:<span class="asterisk">*</span></label>' +
                    '<div class="col-sm-7">' +
                    '<select class="form-control user-status" >' + (function (o) {
                        var str = ""

                        for (var i = 0; i < o.length; i++) {
                            str += '<option value="' + o[i].r + '" >' + o[i].t + '</option>'

                        }
                        return str

                    })(_role) + '</select>' +
                    '<div class="error alert alert-danger" ><strong></strong></div></div>' +
                    '</div>';

            })(window.localStorage.getItem('role'))
            + '</div>'
    }

    function layerUserRole(currole) {
        return '<div style="padding: 10px 0"> ' +
            (function (role) {
                var _role = roleList(role)

                return '<div class="form-group">' +
                    '<label class="col-sm-3 control-label">权限:<span class="asterisk">*</span></label>' +
                    '<div class="col-sm-7">' +
                    '<select class="form-control user-status" >' + (function (o) {
                        var str = ""

                        for (var i = 0; i < o.length; i++) {
                            str += '<option  value="' + o[i].r + '"' + (o[i].r == currole ? "selected" : "" ) + '>' + o[i].t + '</option>'

                        }
                        return str

                    })(_role) + '</select></div></div>';

            })(window.localStorage.getItem('role'))
            + '</div>'
    }

    var divide = {
        "4": 100,
        "3": 70,
        "6": 50,
        "7": 40,
        "8": 20,
        "9": 10
    }

    function fgproportion(_ep, _role) {
        var role = window.localStorage.getItem('role')
        return '<div style="padding: 10px 0"> ' +
            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">吃成比例:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7">' +
            '<input type="text"  class="form-divide form-control user-earningsPercent" value="' + _ep + '">' +
            '<div class=" alert alert-info mt10" ><strong>吃成本比例1~' + divide[_role] + '%</strong></div>' +
            '</div>' +
            '</div>' +
            '</div>';
    }

    function pageInit(requestData) {
        // console.log(requestData)
        var pageInit_layer = layer.load(0);
        $.restPost('/user/doPageQuery', requestData).done(function (msg, data) {
            layer.close(pageInit_layer)
            // console.log(msg, data)


            $("#member-table tbody").html(memberTbody(data.list))

            $("#addUser").off("click").on("click", function () {
                $.rootOpenDialog({
                    title: "新增用户",
                    btn: ["提交"],
                    content: layerUserSet(data.list, {
                        invCode: "",
                        userName: "",
                        passWord: "123456"
                    }),
                    yes: function (index, lay) {
                        var $lay = $(lay)
                        // console.log($lay.find(".room-title").val())
                        var addUser_layerload = layer.load(0);
                        $.restPost('/user/doRegister', {
                            invCode: window.localStorage.getItem('invCode'),
                            userName: $(".user-userName").val(),
                            passWord: $(".user-passWord").val(),
                            role: $lay.find(".user-status").val()

                        }).done(function (msg, data) {
                            layer.close(addUser_layerload)
                            layer.close(index)
                            $.rootSuccessDialog("新增成功", 2000)
                            pageInit(requestData);
                        }).fail(function (msg) {
                            layer.close(addUser_layerload)
                            $.rootErrorDialog("新增失败", 2000)
                        })
                    }


                });

            })

            $(".userUpdate").off("click").on("click", function () {
                var _id = $(this).parents("tr").attr("data-id")
                var _role = $(this).parents("tr").attr("data-role")

                $.rootOpenDialog({
                    title: "修改权限",
                    btn: ["提交"],
                    content: layerUserRole(_role),
                    yes: function (index, lay) {
                        console.log(lay, $(lay).find(".user-status").val())
                        var userUpdate_layerload = layer.load(0);
                        $.restPost('/user/doUpdateUserInfo', {
                            id: _id,
                            token: window.localStorage.getItem('token'),
                            role: $(lay).find(".user-status").val()

                        }).done(function (msg, data) {
                            layer.close(userUpdate_layerload)
                            layer.close(index)
                            $.rootSuccessDialog("更新成功", 2000)
                            pageInit(requestData);
                        }).fail(function (msg) {
                            layer.close(userUpdate_layerload)
                            $.rootErrorDialog("更新失败", 2000)
                        })
                    }


                });


            })

            $(".chichen").off("click").on("click", function () {
                var _id = $(this).parents("tr").attr("data-id")
                var _ep = $(this).parents("tr").attr("data-ep")
                var _role = $(this).parents("tr").attr("data-role")


                $.rootOpenDialog({
                    title: "吃成",
                    btn: ["提交"],
                    content: fgproportion(_ep, _role),
                    yes: function (index, lay) {

                        var _divideval = parseFloat($(lay).find(".form-divide").val());


                        function commit() {
                            var chichen_layerload = layer.load(0);
                            $.restPost('/user/doUpdateUserInfo', {
                                id: _id,
                                token: window.localStorage.getItem('token'),
                                earningsPercent: $(lay).find(".user-earningsPercent").val()

                            }).done(function (msg, data) {
                                layer.close(chichen_layerload)
                                layer.close(index)
                                $.rootSuccessDialog("更新成功", 2000)
                                pageInit(requestData);
                            }).fail(function (msg) {
                                layer.close(chichen_layerload)
                                $.rootErrorDialog("更新失败", 2000)
                            })
                        }

                        var _reg = new RegExp("^[1-9]\\d*$");

                        if(!_reg.test(_divideval)){

                            $.rootErrorDialog('必须是整数', 2000);
                            return
                        }
                        if (_divideval >= 1 && _divideval <= divide[_role]) {
                            commit()
                        } else {
                            $.rootErrorDialog('请填写1~' + divide[_role] + '%范围', 2000)
                        }

                    }


                });


            })

            $(".addjf").off("click").on("click", function () {
                var _id = $(this).parents('tr').attr('data-id')
                $.rootOpenDialog({
                    title: "添加",
                    btn: ["提交"],
                    content: '<div style="padding: 10px 0"> ' +
                    '<div class="form-group">' +
                    '<label class="col-sm-3 control-label">添加积分:<span class="asterisk">*</span></label>' +
                    '<div class="col-sm-7">' +
                    '<input id="ipaddjf" type="tel"  class="form-control">' +
                    '<div class="error alert alert-danger" ><strong></strong></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>',
                    yes: function (index) {
                        var _val = $("#ipaddjf").val()
                        var addjf_layerload = layer.load(0);
                        $.restPost('/deal/doRecharge', {
                            token: window.localStorage.getItem('token'),
                            uId: _id,
                            betAccount: _val
                        }).done(function (msg, data) {
                            layer.close(addjf_layerload)
                            layer.close(index)
                            $.rootSuccessDialog(msg, 2000)
                            pageInit(requestData);
                        }).fail(function () {
                            layer.close(addjf_layerload)
                            $.rootErrorDialog(msg, 2000)
                        })

                    }


                });
            });

            $(".remjf").off("click").on("click", function () {
                var _id = $(this).parents('tr').attr('data-id')
                $.rootOpenDialog({
                    title: "核销",
                    btn: ["提交"],
                    content: '<div style="padding: 10px 0"> ' +
                    '<div class="form-group">' +
                    '<label class="col-sm-3 control-label">核销积分:<span class="asterisk">*</span></label>' +
                    '<div class="col-sm-7">' +
                    '<input id="ipaddjf" type="tel"  class="form-control">' +
                    '<div class="error alert alert-danger" ><strong></strong></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>',
                    yes: function (index) {
                        var _val = $("#ipaddjf").val()
                        var remjf_layerload = layer.load(0);
                        $.restPost('/deal/doConsume', {
                            token: window.localStorage.getItem('token'),
                            uId: _id,
                            betAccount: _val
                        }).done(function (msg, data) {
                            layer.close(remjf_layerload)
                            layer.close(index)
                            $.rootSuccessDialog(msg, 2000)
                            pageInit(requestData);
                        }).fail(function (msg) {
                            layer.close(remjf_layerload)
                            $.rootErrorDialog(msg, 2000)
                        })

                    }


                });
            })

            $("#queryDatum").off("click").on("click", function () {
                queryDatum()
            });

            $("#resetDatum").off("click").on("click", function () {
                resetDatum()
            });
            //显示分页
            laypage({
                cont: 'page', //容器。
                pages: data.pages, //通过后台拿到的总页数
                curr: requestData.pageNum || 1, //当前页
                skip: true, //是否开启跳页
                skin: 'molv', //皮肤,
                jump: function (obj, first) { //触发分页后的回调
                    requestData.pageNum = obj.curr;
                    if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
                        // console.log(pageInit)
                        pageInit(requestData);
                    }
                }
            });


        })
    }


    function queryDatum() {
        pageInit({
            pageNum: 1,
            pageSize: 10,
            token: window.localStorage.getItem('token'),
            realName: $("#realName").val() || "",
            username: $("#username").val() || "",
            referrer: $("#referrer").val() || ""
        });
    }

    function resetDatum() {
        pageInit({
            pageNum: 1,
            pageSize: 10,
            token: window.localStorage.getItem('token')
        });
    }

    pageInit({
        pageNum: 1,
        pageSize: 10,
        token: window.localStorage.getItem('token')
    });
});
